package club.kingyin.kyblogprogateway.core;

import club.kingyin.commons.clients.UserClient;
import club.kingyin.commons.entity.user.Log;
import club.kingyin.commons.response.Result;
import club.kingyin.commons.utils.AspectUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.CompletableFuture;

// 有异步请求的日志链追加到请求响应中
@Aspect
@Component
public class LogAspect {

    @Autowired
    private UserClient userClient;

    @Pointcut("@annotation(club.kingyin.commons.annotation.Log)")
    public void pt(){}

    @Around("pt()")
    public Object logDefault(ProceedingJoinPoint joinPoint) throws Throwable {
        Log log = AspectUtils.paramsObjectOne(joinPoint, Log.class);
        CompletableFuture<Result> proceed = (CompletableFuture<Result>) joinPoint.proceed();
        proceed.whenCompleteAsync((result, throwable) -> {
            log.setResponse(result);
            userClient.appendResponse(log);
        });
        return null;
    }

}
